ibm-watson-machine-learning¶This notebook contains the steps and code to demonstrate support of AutoAI experiments for timeseries data sets in Watson Machine Learning service. It introduces commands for data retrieval, training experiments, persisting pipelines, testing pipelines, deploying pipelines, and scoring.
Some familiarity with Python is helpful. This notebook uses Python 3.10.
The learning goals of this notebook are:
This notebook contains the following parts:
Before you use the sample code in this notebook, you must perform the following setup tasks:
Authenticate the Watson Machine Learning service on IBM Cloud. You need to provide Cloud API key and location.
Tip: Your Cloud API key can be generated by going to the Users section of the Cloud console. From that page, click your name, scroll down to the API Keys section, and click Create an IBM Cloud API key. Give your key a name and click Create, then copy the created key and paste it below. You can also get a service specific url by going to the Endpoint URLs section of the Watson Machine Learning docs. You can check your instance location in your Watson Machine Learning (WML) Service instance details.
You can use IBM Cloud CLI to retrieve the instance location.
ibmcloud login --apikey API_KEY -a https://cloud.ibm.com
ibmcloud resource service-instance WML_INSTANCE_NAME
NOTE: You can also get a service specific apikey by going to the Service IDs section of the Cloud Console. From that page, click Create, and then copy the created key and paste it in the following cell.
Action: Enter your api_key and location in the following cell.
api_key = 'PUT_YOUR_KEY_HERE'
location = 'PASTE YOUR INSTANCE LOCATION HERE'
wml_credentials = {
"apikey": api_key,
"url": 'https://' + location + '.ml.cloud.ibm.com'
}
!pip install -U ibm-watson-machine-learning | tail -n 1
!pip install wget | tail -n 1
!pip install plotly | tail -n 1
Successfully installed ibm-watson-machine-learning-1.0.292 Successfully installed wget-3.2 Requirement already satisfied: tenacity>=6.2.0 in /opt/conda/envs/Python-3.10/lib/python3.10/site-packages (from plotly) (8.0.1)
from ibm_watson_machine_learning import APIClient
client = APIClient(wml_credentials)
You need to create a space that will be used for your work. If you do not have a space, you can use Deployment Spaces Dashboard to create one.
space_id and paste it belowTip: You can also use SDK to prepare the space for your work. More information can be found here.
Action: assign space ID below
space_id = 'PASTE YOUR SPACE ID HERE'
You can use the list method to print all existing spaces.
client.spaces.list(limit=10)
To be able to interact with all resources available in Watson Machine Learning, you need to set the space which you will be using.
client.set.default_space(space_id)
'SUCCESS'
In next cell we read the COS credentials from the space.
cos_credentials = client.spaces.get_details(space_id=space_id)['entity']['storage']['properties']
Download training data from git repository and upload it to a COS.
This example uses the Electricity_daily.
datasource_name = 'bluemixcloudobjectstorage'
bucketname = cos_credentials['bucket_name']
import os, wget, zipfile
filename = 'electricity_usage.csv'
base_url = 'https://raw.githubusercontent.com/IBM/watson-machine-learning-samples/master/cloud/data/electricity/'
if not os.path.isfile(filename): wget.download(base_url + filename)
import plotly.express as px
import pandas as pd
df = pd.read_csv(filename)
fig = px.line(df, x='date', y=df.columns)
fig.show()
conn_meta_props= {
client.connections.ConfigurationMetaNames.NAME: f"Connection to Database - {datasource_name} ",
client.connections.ConfigurationMetaNames.DATASOURCE_TYPE: client.connections.get_datasource_type_uid_by_name(datasource_name),
client.connections.ConfigurationMetaNames.DESCRIPTION: "Connection to external Database",
client.connections.ConfigurationMetaNames.PROPERTIES: {
'bucket': bucketname,
'access_key': cos_credentials['credentials']['editor']['access_key_id'],
'secret_key': cos_credentials['credentials']['editor']['secret_access_key'],
'iam_url': 'https://iam.cloud.ibm.com/identity/token',
'url': cos_credentials['endpoint_url']
}
}
conn_details = client.connections.create(meta_props=conn_meta_props)
Creating connections... SUCCESS
Note: The above connection can be initialized alternatively with api_key and resource_instance_id.
The above cell can be replaced with:
conn_meta_props= {
client.connections.ConfigurationMetaNames.NAME: f"Connection to Database - {db_name} ",
client.connections.ConfigurationMetaNames.DATASOURCE_TYPE: client.connections.get_datasource_type_uid_by_name(db_name),
client.connections.ConfigurationMetaNames.DESCRIPTION: "Connection to external Database",
client.connections.ConfigurationMetaNames.PROPERTIES: {
'bucket': bucket_name,
'api_key': cos_credentials['apikey'],
'resource_instance_id': cos_credentials['resource_instance_id'],
'iam_url': 'https://iam.cloud.ibm.com/identity/token',
'url': 'https://s3.us.cloud-object-storage.appdomain.cloud'
}
}
conn_details = client.connections.create(meta_props=conn_meta_props)
connection_id = client.connections.get_uid(conn_details)
The code in next cell defines connections to created assets.
from ibm_watson_machine_learning.helpers import DataConnection, S3Location
data_connections = []
data_connection = DataConnection(
connection_asset_id=connection_id,
location=S3Location(bucket=cos_credentials['bucket_name'],
path=filename)
)
data_connection.set_client(client)
data_connection.write(data=filename, remote_name=filename)
data_connections.append(data_connection)
Provide the input information for AutoAI optimizer:
name - experiment nameprediction_type - type of the problemtimestamp_column_name - date&time column name/indexfeature_columns - names/indices of supporting feature columnspipeline_types - types of the pipelinesfrom ibm_watson_machine_learning.experiment import AutoAI
from ibm_watson_machine_learning.utils.autoai.enums import TimeseriesAnomalyPredictionPipelineTypes
experiment = AutoAI(wml_credentials, space_id=space_id)
pipeline_optimizer = experiment.optimizer(
name="Electricity usage anomalies prediction",
prediction_type=AutoAI.PredictionType.TIMESERIES_ANOMALY_PREDICTION,
timestamp_column_name='date',
feature_columns=['industry_a_usage'],
pipeline_types=[TimeseriesAnomalyPredictionPipelineTypes.PointwiseBoundedBATS,
TimeseriesAnomalyPredictionPipelineTypes.PointwiseBoundedBATSForceUpdate,
TimeseriesAnomalyPredictionPipelineTypes.PointwiseBoundedHoltWintersAdditive,
TimeseriesAnomalyPredictionPipelineTypes.WindowLOF,
TimeseriesAnomalyPredictionPipelineTypes.WindowNN,
TimeseriesAnomalyPredictionPipelineTypes.WindowPCA]
)
Configuration parameters can be retrieved via pipeline_optimizer.get_params().
Call the fit() method to trigger the AutoAI experiment. You can either use interactive mode (synchronous job) or background mode (asychronous job) by specifying background_model=True.
fit_details = pipeline_optimizer.fit(training_data_reference=data_connections, background_mode=False)
Training job fab41e99-dc51-480c-b5d8-f9b5793163e7 completed: 100%|████████| [01:56<00:00, 1.17s/it]
You can use the get_run_status() method to monitor AutoAI jobs in background mode.
pipeline_optimizer.get_run_status()
'completed'
You can list trained pipelines and evaluation metrics information in
the form of a Pandas DataFrame by calling the summary() method. You can
use the DataFrame to compare all discovered pipelines and select the one
you like for further deployment.
summary = pipeline_optimizer.summary()
summary
| Enhancements | Estimator | Winner | aggregated_score | average_precision_LevelShift | average_precision_LocalizedExtreme | average_precision_Trend | average_precision_Variance | f1_LevelShift | f1_LocalizedExtreme | ... | precision_Trend | precision_Variance | recall_LevelShift | recall_LocalizedExtreme | recall_Trend | recall_Variance | roc_auc_LevelShift | roc_auc_LocalizedExtreme | roc_auc_Trend | roc_auc_Variance | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Pipeline Name | |||||||||||||||||||||
| Pipeline_4 | HPO, FE | Window | True | 14.0 | 1.000000 | 0.070139 | 0.403380 | 0.869842 | 0.834432 | 0.166667 | ... | 0.666667 | 1.000000 | 0.716667 | 0.333333 | 1.00 | 0.846154 | 1.000000 | 0.634181 | 0.923097 | 0.965492 |
| Pipeline_1 | HPO, FE | Forecasting | True | 11.5 | 1.000000 | 0.052783 | 0.818322 | 0.569901 | 0.532218 | 0.023810 | ... | 0.385397 | 0.280672 | 1.000000 | 0.166667 | 1.00 | 0.538462 | 1.000000 | 0.622881 | 0.990741 | 0.728253 |
| Pipeline_5 | HPO, FE | Window | True | 10.0 | 0.704441 | 0.081628 | 0.383347 | 0.845679 | 0.775714 | 0.058061 | ... | 0.472710 | 0.380410 | 0.637500 | 0.833333 | 0.75 | 0.974359 | 0.778339 | 0.750000 | 0.913580 | 0.955188 |
3 rows × 24 columns
Check pipeline details by calling get_pipeline_details(). By default details of best pipeline are returned.
best_pipeline_name = summary[summary.Winner==True].index.values[0]
print('Best pipeline is:', best_pipeline_name)
pipeline_details = pipeline_optimizer.get_pipeline_details()
pipeline_details
Best pipeline is: Pipeline_4
{'composition_steps': ['Flatten'],
'pipeline_nodes': ['Flatten', 'Window'],
'tsad_metrics': score
holdout {'agg': {'average_precision': {'LevelShift': {...}
import json
# Check the metrics details
print(json.dumps(pipeline_details["tsad_metrics"].iloc[0,0], indent=4, sort_keys=True))
{
"agg": {
"average_precision": {
"LevelShift": {
"mean": 1.0,
"range": [
1.0,
1.0
]
},
"LocalizedExtreme": {
"mean": 0.07013888888888889,
"range": [
0.041666666666666664,
0.11666666666666667
]
},
"Trend": {
"mean": 0.40337961163554553,
"range": [
0.3932949854582981,
0.4129651641358298
]
},
"Variance": {
"mean": 0.8698422582327617,
"range": [
0.7908484228322286,
0.9819004524886878
]
}
},
"f1": {
"LevelShift": {
"mean": 0.8344322344322345,
"range": [
0.8,
0.8571428571428571
]
},
"LocalizedExtreme": {
"mean": 0.16666666666666666,
"range": [
0.0,
0.25
]
},
"Trend": {
"mean": 0.8000000000000002,
"range": [
0.8,
0.8
]
},
"Variance": {
"mean": 0.9127272727272727,
"range": [
0.8181818181818181,
0.9600000000000001
]
}
},
"precision": {
"LevelShift": {
"mean": 1.0,
"range": [
1.0,
1.0
]
},
"LocalizedExtreme": {
"mean": 0.1111111111111111,
"range": [
0.0,
0.16666666666666666
]
},
"Trend": {
"mean": 0.6666666666666666,
"range": [
0.6666666666666666,
0.6666666666666666
]
},
"Variance": {
"mean": 1.0,
"range": [
1.0,
1.0
]
}
},
"recall": {
"LevelShift": {
"mean": 0.7166666666666667,
"range": [
0.6666666666666666,
0.75
]
},
"LocalizedExtreme": {
"mean": 0.3333333333333333,
"range": [
0.0,
0.5
]
},
"Trend": {
"mean": 1.0,
"range": [
1.0,
1.0
]
},
"Variance": {
"mean": 0.8461538461538461,
"range": [
0.6923076923076923,
0.9230769230769231
]
}
},
"roc_auc": {
"LevelShift": {
"mean": 1.0,
"range": [
1.0,
1.0
]
},
"LocalizedExtreme": {
"mean": 0.634180790960452,
"range": [
0.4406779661016949,
0.9067796610169491
]
},
"Trend": {
"mean": 0.9230967078189302,
"range": [
0.9197530864197531,
0.9259259259259259
]
},
"Variance": {
"mean": 0.96549245147376,
"range": [
0.9252336448598131,
0.9971243709561467
]
}
}
},
"aggregated_score": [
{
"P4": 14.0
},
{
"P1": 11.5
},
{
"P5": 10.0
},
{
"P2": 9.5
},
{
"P6": 8.0
},
{
"P3": 7.0
}
],
"iterations": [
{
"average_precision": {
"LevelShift": 1.0,
"LocalizedExtreme": 0.11666666666666667,
"Trend": 0.4038786853125088,
"Variance": 0.8367778993773689
},
"f1": {
"LevelShift": 0.8571428571428571,
"LocalizedExtreme": 0.25,
"Trend": 0.8,
"Variance": 0.9600000000000001
},
"precision": {
"LevelShift": 1.0,
"LocalizedExtreme": 0.16666666666666666,
"Trend": 0.6666666666666666,
"Variance": 1.0
},
"recall": {
"LevelShift": 0.75,
"LocalizedExtreme": 0.5,
"Trend": 1.0,
"Variance": 0.9230769230769231
},
"roc_auc": {
"LevelShift": 1.0,
"LocalizedExtreme": 0.9067796610169491,
"Trend": 0.9236111111111112,
"Variance": 0.9741193386053199
}
},
{
"average_precision": {
"LevelShift": 1.0,
"LocalizedExtreme": 0.05208333333333333,
"Trend": 0.4129651641358298,
"Variance": 0.9819004524886878
},
"f1": {
"LevelShift": 0.846153846153846,
"LocalizedExtreme": 0.25,
"Trend": 0.8,
"Variance": 0.9600000000000001
},
"precision": {
"LevelShift": 1.0,
"LocalizedExtreme": 0.16666666666666666,
"Trend": 0.6666666666666666,
"Variance": 1.0
},
"recall": {
"LevelShift": 0.7333333333333333,
"LocalizedExtreme": 0.5,
"Trend": 1.0,
"Variance": 0.9230769230769231
},
"roc_auc": {
"LevelShift": 1.0,
"LocalizedExtreme": 0.5550847457627119,
"Trend": 0.9259259259259259,
"Variance": 0.9971243709561467
}
},
{
"average_precision": {
"LevelShift": 1.0,
"LocalizedExtreme": 0.041666666666666664,
"Trend": 0.3932949854582981,
"Variance": 0.7908484228322286
},
"f1": {
"LevelShift": 0.8,
"LocalizedExtreme": 0.0,
"Trend": 0.8,
"Variance": 0.8181818181818181
},
"precision": {
"LevelShift": 1.0,
"LocalizedExtreme": 0.0,
"Trend": 0.6666666666666666,
"Variance": 1.0
},
"recall": {
"LevelShift": 0.6666666666666666,
"LocalizedExtreme": 0.0,
"Trend": 1.0,
"Variance": 0.6923076923076923
},
"roc_auc": {
"LevelShift": 1.0,
"LocalizedExtreme": 0.4406779661016949,
"Trend": 0.9197530864197531,
"Variance": 0.9252336448598131
}
}
],
"supporting_rank": {
"average_precision": {
"LevelShift": {
"P1": 2.0,
"P2": 2.0,
"P3": 6.0,
"P4": 2.0,
"P5": 4.0,
"P6": 5.0
},
"LocalizedExtreme": {
"P1": 4.0,
"P2": 5.0,
"P3": 1.0,
"P4": 3.0,
"P5": 2.0,
"P6": 6.0
},
"Trend": {
"P1": 1.5,
"P2": 1.5,
"P3": 6.0,
"P4": 4.0,
"P5": 5.0,
"P6": 3.0
},
"Variance": {
"P1": 5.0,
"P2": 6.0,
"P3": 4.0,
"P4": 1.0,
"P5": 3.0,
"P6": 2.0
}
}
}
}
In this section you will learn how to deploy and score pipeline model as online deployment using WML instance.
from ibm_watson_machine_learning.deployment import WebService
service = WebService(wml_credentials, source_space_id=space_id)
service.create(
experiment_run_id=pipeline_optimizer.get_run_details()['metadata']['id'],
model=best_pipeline_name,
deployment_name="Electricity usage anomalies prediction"
)
Preparing an AutoAI Deployment... Published model uid: 1cb20b02-e5e3-4561-b212-32ca8b93dad8 Deploying model 1cb20b02-e5e3-4561-b212-32ca8b93dad8 using V4 client. ####################################################################################### Synchronous deployment creation for uid: '1cb20b02-e5e3-4561-b212-32ca8b93dad8' started ####################################################################################### initializing Note: online_url is deprecated and will be removed in a future release. Use serving_urls instead. .. ready ------------------------------------------------------------------------------------------------ Successfully finished deployment creation, deployment_uid='bb7651a8-f386-493f-aa60-c91338bc4600' ------------------------------------------------------------------------------------------------
To show all available information about the deployment use the .get_params() method:
service.get_params()
Note: online_url is deprecated and will be removed in a future release. Use serving_urls instead.
{'entity': {'asset': {'id': '1cb20b02-e5e3-4561-b212-32ca8b93dad8'},
'custom': {},
'deployed_asset_type': 'model',
'hybrid_pipeline_hardware_specs': [{'hardware_spec': {'name': 'S',
'num_nodes': 1},
'node_runtime_id': 'auto_ai.tsad'}],
'name': 'Electricity usage anomalies prediction',
'online': {},
'space_id': '3af17fad-fc7b-4507-ad3f-26c7de6479d8',
'status': {'online_url': {'url': 'https://yp-qa.ml.cloud.ibm.com/ml/v4/deployments/bb7651a8-f386-493f-aa60-c91338bc4600/predictions'},
'serving_urls': ['https://yp-qa.ml.cloud.ibm.com/ml/v4/deployments/bb7651a8-f386-493f-aa60-c91338bc4600/predictions'],
'state': 'ready'}},
'metadata': {'created_at': '2023-04-04T13:36:40.623Z',
'id': 'bb7651a8-f386-493f-aa60-c91338bc4600',
'modified_at': '2023-04-04T13:36:40.623Z',
'name': 'Electricity usage anomalies prediction',
'owner': 'IBMid-270005A11W',
'space_id': '3af17fad-fc7b-4507-ad3f-26c7de6479d8'},
'system': {'warnings': [{'id': 'Deprecated',
'message': 'online_url is deprecated and will be removed in a future release. Use serving_urls instead.'}]}}
You can use the score method to get predictions for defined forecasting window. You can either send payload records or use empty list.
filename = 'electricity_usage_new.csv'
if not os.path.isfile(filename): wget.download(base_url + filename)
newData= pd.read_csv(filename)
predictions = service.score(newData.drop(columns=['date', 'label'], axis=1))
predictions
{'predictions': [{'fields': ['prediction'],
'values': [[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[-1]],
[[-1]],
[[-1]],
[[-1]],
[[-1]],
[[-1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[-1]],
[[-1]],
[[-1]],
[[-1]],
[[-1]],
[[-1]],
[[-1]],
[[-1]],
[[-1]],
[[-1]],
[[-1]],
[[-1]],
[[-1]],
[[-1]],
[[-1]],
[[-1]],
[[-1]],
[[-1]],
[[-1]],
[[-1]],
[[-1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[-1]],
[[-1]],
[[-1]],
[[-1]],
[[-1]],
[[-1]],
[[-1]],
[[-1]],
[[-1]],
[[-1]],
[[-1]],
[[-1]],
[[-1]],
[[-1]],
[[-1]],
[[-1]],
[[-1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]],
[[1]]]}]}
prediction_values = [pred[0][0] for pred in predictions['predictions'][0]['values']]
pred_df = pd.DataFrame({'date' : pd.to_datetime(newData['date']),
'industry_a_usage' : newData['industry_a_usage'],
'label': newData['label'],
'predictions' : prediction_values})
fig = px.line(pred_df, x='date', y=['industry_a_usage'])
x_labels = pred_df[(pred_df['label'] == -1)]['date']
y_labels = pred_df[(pred_df['label'] == -1)]['industry_a_usage']
fig.add_scatter(x=x_labels, y=y_labels, mode='markers', marker=dict(color='green', symbol='x',size=10))
x_predictions = pred_df[pred_df['predictions'] == -1]['date']
y_predictions = pred_df[pred_df['predictions'] == -1]['industry_a_usage']
fig.add_scatter(x=x_predictions, y=y_predictions,mode='markers', marker=dict(color='red', symbol='circle-dot'))
fig.data[1].name = "anomalies"
fig.data[2].name = "predicted_as_anomalies"
fig.show()
If you want to clean up all created assets:
please follow up this sample notebook.
You successfully completed this notebook!.
You learned how to use ibm-watson-machine-learning to run AutoAI experiments.
Check out our Online Documentation for more samples, tutorials, documentation, how-tos, and blog posts.
Jun Wang, is a Software Architect and Data Scientist at IBM with a track record of developing enterprise-level applications that substantially increases clients' ability to turn data into actionable knowledge.
Copyright © 2023 IBM. This notebook and its source code are released under the terms of the MIT License.